package com.yanfan.iot.tdengine.init;


import com.alibaba.druid.pool.DruidDataSource;
import com.yanfan.iot.tdengine.config.TDengineConfig;
import com.yanfan.iot.tdengine.dao.TDDeviceLogDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 类名: ApplicationStarted
 * 时间: 2022/5/18,0018 1:41
 * 开发人: wxy
 */
@Component
public class ApplicationStarted {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationStarted.class);

    @Autowired
    private ApplicationContext applicationContext;

    private DruidDataSource dataSource;

    private TDengineConfig dengineConfig;

    private TDDeviceLogDao deviceLogMapper;


    @PostConstruct
    public void run() {
        //先获取TDengine的配置，检测TDengine是否已经配置
        if (containBean(TDengineConfig.class)) {
            this.dengineConfig = applicationContext.getBean(TDengineConfig.class);
            this.dataSource = applicationContext.getBean("tDengineDataSource", DruidDataSource.class);
            this.deviceLogMapper = applicationContext.getBean(TDDeviceLogDao.class);
            initTDengine(this.dengineConfig.getDbName());
            logger.info("使用TDengine存储设备数据，初始化成功");
        } else {
            logger.info("使用MySql存储设备数据，初始化成功");
        }
    }

    /**
     * @return
     * @Method
     * @Description 开始初始化加载系统参数, 创建数据库和超级表
     * @Param null
     * @date 2022/5/22,0022 14:27
     * @author wxy
     */
    public void initTDengine(String dbName) {
        try {
            dengineConfig.createDatabase();
            //创建数据库表
            deviceLogMapper.createSTable(dbName);
            logger.info("完成超级表的创建");
        } catch (Exception e) {
            logger.error("错误", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * @return
     * @Method containBean
     * @Description 根据类判断是否有对应bean
     * @Param 类
     * @date 2022/5/22,0022 14:12
     * @author wxy
     */
    private boolean containBean(@Nullable Class<?> T) {
        String[] beans = applicationContext.getBeanNamesForType(T);
        if (beans == null || beans.length == 0) {
            return false;
        } else {
            return true;
        }
    }
}
